package com.example.mylibrary.network

import com.example.mylibrary.utils.SpUtils
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.Response

class HeaderInterceptor : Interceptor {
    private var headers: MutableMap<String, String> = mutableMapOf<String, String>()

    // 无参构造
    constructor()

    constructor(headers: HashMap<String, String>?) {
        if (headers != null) {
            this.headers = headers
        }
    }

    fun setHeaders(headers: MutableMap<String, String>) {
        this.headers = headers
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        // 调用网络请求的时候回调用这个方法,
        var request = chain.request()
        val oldUrl = request.url
        val requestBuilder = request.newBuilder()
        val urlHeaders = request.headers(UrlConfig.NEW_HEADER_NAME)
        if (!urlHeaders.isNullOrEmpty()) {
            requestBuilder.removeHeader(UrlConfig.NEW_HEADER_NAME)
            val httpUrl = when (urlHeaders[0]) {
                // 普通http请求,请求头过滤,替换url
                UrlConfig.NEW_HEADER_VALUE -> {
                    UrlConfig.PUBLIC_BASE_URL.toHttpUrl()

                }
                // 更换私有云,过滤请求头替换url
                UrlConfig.NEW_HEADER_PRIVATE -> {
                    val host = SpUtils.get("host", "") as String
                    val port = SpUtils.get("port", "") as String
                    "http://$host:$port/".toHttpUrl()
                }
                else -> {
                    oldUrl
                }
            }

            val newHttpUrl = oldUrl
                .newBuilder()
                .host(httpUrl.host)
                .port(httpUrl.port)
                .build()
            // 替换新url时,更新header中host
            requestBuilder.addHeader("HOST", httpUrl.host)
            requestBuilder.url(newHttpUrl)
        }

        // 如果传递过来的是多个header信息,遍历添加header
        if (!headers.isNullOrEmpty()) {
            val keys = headers.keys
            for (key in keys) {
                val value = headers[key]
                value?.let { requestBuilder.addHeader(key, it) }
            }
        }
        request = requestBuilder.build()
        return chain.proceed(request)
    }

}